<template>
  <view class="">
    <scroll-view scroll-y="true" class="scroll-wrapper">
      <u-navbar :is-back="true" title="填写设备信息" :border-bottom="false"></u-navbar>
      <!-- #ifndef MP-WEIXIN -->
      <u-image width="100%" height="350rpx" :src="src"></u-image>
      <!-- #endif -->
      <view class="wrap">
        <u-form :model="model" :rules="rules" ref="uForm" :errorType="errorType">
          <u-form-item :label-position="labelPosition" label="设备名称" prop="name" label-width="180"
                      :leftIconStyle="{color:'#d5d5d5'}" required>
            <u-input :border="border" type="select" :select-open="selectShow" v-model="model.name"
                     placeholder="请选择设备名称(必选)" @click="selectShow = true"></u-input>
          </u-form-item>
          <u-form-item :label-position="labelPosition" label="设备位置" prop="address" label-width="180"
                       :leftIconStyle="{color:'#d5d5d5'}" right-icon="map"
                       :rightIconStyle="{color:'#d5d5d5'}" required>
            <u-input :border="border" placeholder="请在地图选择详细地址" v-model="model.address" type="text" disabled
                     @click="chooseAddress"></u-input>
          </u-form-item>
          <u-form-item :label-position="labelPosition" label="设备型号" prop="specification" label-width="180" :leftIconStyle="{color:'#d5d5d5'}"
                       required>
            <u-input :border="border" placeholder="请输入设备型号(必填)" v-model="model.specification" type="text"></u-input>
          </u-form-item>
          <u-form-item :label-position="labelPosition" label="车辆资料" label-width="150" required>
            <u-upload
                :custom-btn="true" ref="uUpload" :auto-upload="true" :action="action" :max-size="10 * 1024 * 1024" max-count="9" width="160" height="160" :size-type="siteType">
              <view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
                <u-icon name="plus" size="60" :color="$u.color['lightColor']"></u-icon>
              </view>
            </u-upload>
          </u-form-item>

          <u-line color="red" />
          <u-form-item :label-position="labelPosition" label="车牌号" prop="plateNumber" label-width="180"
                       left-icon="home" :leftIconStyle="{color:'#d5d5d5'}">
            <u-input :border="border" placeholder="请输入车牌号(必填)" v-model="model.plateNumber" type="text"></u-input>
          </u-form-item>

          <u-form-item :label-position="labelPosition" label="设备厂家" prop="factory" label-width="180"
                       left-icon="eye" :leftIconStyle="{color:'#d5d5d5'}">
            <u-input :border="border" placeholder="请输设备厂家(必填)" v-model="model.factory" type="text"></u-input>
          </u-form-item>
          <u-form-item :label-position="labelPosition" label="出厂日期" prop="factoryDate" label-width="180"
                       left-icon="clock" :leftIconStyle="{color:'#d5d5d5'}">
            <u-input :border="border" placeholder="请输设备厂家(必填)" v-model="model.factoryDate" type="text" @click="dateClick"></u-input>
          </u-form-item>
          <u-form-item label-width="150" :label-position="labelPosition" label="设备描述" left-icon="bookmark">
            <u-input type="textarea" :border="border" v-model="model.description" placeholder="请填写设备描述、设备结算等"/>
          </u-form-item>

          <u-line color="red" />
          <u-form-item :label-position="labelPosition" label="负责人姓名" prop="manager" label-width="180"
                       :leftIconStyle="{color:'#d5d5d5'}" required>
            <u-input :border="border" placeholder="请输入负责人姓名(必填)" v-model="model.manager" type="text"></u-input>
          </u-form-item>
          <u-form-item :label-position="labelPosition" label="负责人电话" prop="managerPhone" label-width="180"
                       :leftIconStyle="{color:'#d5d5d5'}" required>
            <u-input :border="border" placeholder="请输入负责人电话(必填)" v-model="model.managerPhone" type="number"
                     maxlength="11"></u-input>
          </u-form-item>
          <u-form-item :label-position="labelPosition" label="公司名称" prop="companyName" label-width="180"
                       :leftIconStyle="{color:'#d5d5d5'}" required>
            <u-input :border="border" placeholder="请输入公司名称(必填)" v-model="model.companyName" type="text"
                     maxlength="11"></u-input>
          </u-form-item>
          <u-form-item :label-position="labelPosition" label="公司性质" prop="companyNature" label-width="180"
                       :leftIconStyle="{color:'#d5d5d5'}" required>
            <u-input :border="border" placeholder="请输入公司性质(必填)" v-model="model.companyNature" type="text"
                     maxlength="11"></u-input>
          </u-form-item>
        </u-form>
        <!-- 流量主-腾讯视频广告 -->
<!--        <ad unit-id="adunit-c6cdd74f48eed506" ad-type="video" ad-theme="white"></ad>-->
        <u-select mode="single-column" :list="selectList" v-model="selectShow" @confirm="selectConfirm"></u-select>
<!--        <u-select mode="single-column" :list="decorationList" v-model="decorationShow"  @confirm="decorationConfirm"></u-select>-->
        <u-action-sheet :list="actionSheetList" v-model="actionSheetShow" @click="actionSheetCallback"></u-action-sheet>
        <u-calendar v-model="show" :mode="mode" @change="changeDate" max-date="2100-01-01"></u-calendar>
        <u-toast ref="uToast" />
      </view>
    </scroll-view>
    <view class="bottom-btn">
      <u-button type="primary" @click="submit">提交</u-button>
    </view>
  </view>
</template>

<script>
import config from "@/common/config.js"
export default {
  data() {
    let that = this;
    return {
      show: false,
      mode: 'date',

      radioCheckWidth: 'auto',
      radioCheckWrap: false,
      src: 'http://img.sccnn.com/bimg/340/02027.jpg',
      actionSheetShow: false,
      model: {
        name: '',
        address: '',
        specification: '',
        imageList: [],
        plateNumber: '',
        factory: '',
        factoryDate: '',
        description: '',
        //负责人
        manager: '',
        //负责人电话
        managerPhone: '',
        companyName: '',
        companyNature: '',
        tenantId: '',
        source: 'my',
        createName: uni.getStorageSync('lifeData').vuex_user.userName,
        createId: uni.getStorageSync('lifeData').vuex_user.userId,
        longitude: 0,
        latitude: 0,
        location: null,
        used: 0,
        enabled: true,
      },
      selectList: [],
      rules: {
        name: [
          {
            required: true,
            message: '请选择设备名称',
            trigger: ['change', 'blur'],
          }
        ],
        address: [
          {
            required: true,
            message: '请输入设备详细地址',
            trigger: ['change', 'blur'],
          }
        ],
        specification: [
          {
            required: true,
            message: '请输入设备型号',
            trigger: ['change', 'blur'],
          }
        ],
        manager: [
					{
						required: true,
						message: '请输入负责人姓名',
						trigger: ['change','blur'],
					}
				],
        managerPhone: [
					{
						required: true,
						message: '请输入负责人电话',
						trigger: ['change','blur'],
					}
				],
        companyName: [
          {
            required: true,
            message: '请选择公司名称',
            trigger: ['change','blur'],
          }
        ],
        companyNature: [
          {
            required: true,
            message: '请选择公司性质',
            trigger: ['change','blur'],
          }
        ],
      },
      border: false,
      check: false,
      selectShow: false,
      decorationShow: false,
      labelPosition: 'left',
      errorType: ['toast'],
      action: config.staticUrl + '/common/upload',
      siteType:['compressed'],
      dateLabel:'请选择出厂日期',
    };
  },
  onLoad(option) {
    this.findVehicleTypeList()
    // 定位经纬度
    uni.getLocation({
      type: 'gcj02',
      // 当指定 high 时，期望精度值为100m，当指定 best 时期望精度值为20m
      accuracy: 'best',
      // 开启高精度定位
      isHighAccuracy: true,
      success: (res) => {
        this.longitude = res.longitude
        this.latitude = res.latitude
      }
    });
    uni.$on('changeAddressConfig', (address, lon, lat) => {
      // 获取数据
      this.changeAddressConfig(address, lon, lat);
    })
  },
  onUnload() {
    // 移除监听事件
    uni.$off('changeAddressConfig');
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    dateClick() {
      this.show = true
    },
    changeAddressConfig(address, lon, lat) {
      this.model.address = address
      this.model.longitude = lon
      this.model.latitude = lat
      this.model.location=lon+","+lat
    },
    submit() {
      let files = [];
      // 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
      files = this.$refs.uUpload.lists.filter(val => {
        return val.progress == 100;
      })
      if(this.$u.test.isEmpty(files)){
        return this.$mytip.toast('请至少选择一张设备图片')
      }
      let imageList = files.map(val => {
        return {
          imageName: val.response.realName,
          imagePath: val.response.fileName,
          imgUrl: val.response.url,
          imageSize: val.file.size
        }
      })
      this.model.imageList = imageList;

      this.$refs.uForm.validate(valid => {
        if (valid) {
         /* if (!this.$u.test.mobile(this.model.managerPhone)) {
            return this.$mytip.toast('负责人电话请输入手机号码')
          }*/
          let url = "/vehicles";
          if (this.model.id) {
            url = "/vehicles/" + this.model.id;
          }
          this.model.publishId = uni.getStorageSync('lifeData').vuex_user.user.userId;
          this.$u.post(url, this.model).then(data => {
            this.showTips();
            setTimeout(()=>{
              uni.switchTab({
                url: '/pages/vehicle/index'
              });
            },1000);
          });

        } else {
          console.log('验证失败');
        }
      });
    },
    selectConfirm(e) {
      e.map((val, index) => {
        this.model.name = val.label;
        this.model.villageId = val.value
      })
    },

    labelPositionChange(index) {
      this.labelPosition = index == 0 ? 'left' : 'top';
    },
    // 点击actionSheet回调
    actionSheetCallback(index) {
      uni.hideKeyboard();
      this.model.payType = this.actionSheetList[index].text;
    },
    changeDate(e){
      this.model.factoryDate = e.result
      this.dateLabel = e.result
    },
    findVehicleTypeList() {
      this.selectList=[{label:"运输设备",value:"运输设备"}];
     /* let url = "/api/dict/type/car_vehicle_type";
      this.$u.get(url, {
        city: uni.getStorageSync('lifeData').vuex_city,
        orderByColumn: 'name',
        isAsc: 'desc'
      }).then(result => {
        const data = result.data
        for (let i = 0; i < data.length; i++) {
          // 先转成字符串再转成对象，避免数组对象引用导致数据混乱
          let item = data[i]
          this.selectList.push({
            label: item.dictLabel,
            value: item.dictValue
          })
        }
        return data
      });*/
      console.log(this.selectList)
    },
    showTips() {
      this.$refs.uToast.show({
        title: '操作成功',
        type: 'success'
      })
    },
    chooseAddress() {
      this.$u.route({
        url: '/pages/chooseAddress/index'
      })
    },
  }
};
</script>

<style>
page {
  background-color: #FFFFFF;
}
</style>
<style scoped lang="scss">
.wrap {
  padding: 30rpx;
}

.scroll-wrapper {
  position: absolute;
  left: 0rpx;
  right: 0rpx;
  top: 0rpx;
  bottom: 120rpx;
}

.bottom-btn {
  position: fixed;
  bottom: 8rpx;
  width: 100%;
  padding: 30rpx;
  border-top: 1rpx solid #ccc;
  background-color: #FFFFFF;
}

.dateBtn {
  position: absolute;
  right: 0rpx;
  top: 10rpx;
  color: #606266;
}

.slot-btn {
  width: 160rpx;
  height: 160rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgb(244, 245, 246);
  border-radius: 10rpx;
}

.slot-btn__hover {
  background-color: rgb(235, 236, 238);
}

.custom-gap {
  width: 1000rpx;
  height: 10rpx;
  margin: 0 -200rpx 0 -200rpx;
  background-color: rgb(235, 236, 238);
}
</style>
